package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        //设置发布人
        notice.setIssuer(UserContext.getCurrentUser());
        //设置发布时间
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {

        //删除关系表
        noticeMapper.deleteRelation(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        //设置发布时间
        notice.setPubdate(new Date());
        //删除关系表
        noticeMapper.deleteRelation(notice.getId());
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"pubdate desc"); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public Long selectByNoticeIdAndEmpId(Long noticeId, Long empId) {
        Long ret = noticeMapper.selectByNoticeIdAndEmpId(noticeId,empId);
        return ret;
    }

    @Override
    public void insertNoticeIdAndEmpId(Long id, Long empId) {
        Long employeeId = noticeMapper.selectByNoticeIdAndEmpId(id,empId);
        if (employeeId == null){
            noticeMapper.insertNoticeIdAndEmpId(id,empId);
        }
    }
}
